package com.itheima.health.mobile.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.itheima.health.common.MessageConst;
import com.itheima.health.entity.Result;
import com.itheima.health.pojo.Setmeal;
import com.itheima.health.service.SetMealService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.util.List;
import java.util.Set;

@RestController
@RequestMapping("/mobile/setmeal")
@Slf4j
public class SetMealController {

    @Reference
    private SetMealService setMealService;

    @Autowired
    private JedisPool jedisPool;

    /**
     * 查询套餐
     * @return
     */
    @GetMapping("/getSetmeal")
    public Result getSetmeal(){
        List<Setmeal> setmeals = null;
        //先查询缓存中是否有页面数据
        try (Jedis jedis = jedisPool.getResource()) {
            log.debug("[获取jedis对象]:{}",jedis);
            //获取对应所有套餐json字符串
            String jsonString = jedis.get("setmeals");
            if (null != jsonString && !"".equals(jsonString)) {
                //将字符串转化为list对象
                setmeals = JSON.parseArray(jsonString, Setmeal.class);
            } else {
                //若redis中获取字符串为空
                //rpc调用查询所有套餐
                setmeals = setMealService.findAll();
            }
        }
        return new Result(true, MessageConst.GET_SETMEAL_LIST_SUCCESS,setmeals);
    }
    @GetMapping("/findById")
    public Result findById(Integer id){
        Setmeal setmeal = null;
        //先查询redis中是否有缓存
        try (Jedis jedis = jedisPool.getResource()) {
            log.debug("[获取jedis对象]:{}",jedis);
            //获取对应所有套餐json字符串
            String jsonString = jedis.get("setmeal_"+id);
            if (null != jsonString && !"".equals(jsonString)) {
                //将字符串转化为list对象
                setmeal = JSON.parseObject(jsonString,Setmeal.class);
            } else {
                //若redis中获取字符串为空
                //rpc调用查询所有套餐
                setmeal = setMealService.findById(id);
            }
        }
        //返回
        return new Result(true,MessageConst.QUERY_SETMEAL_SUCCESS,setmeal);
    }
}
